package cn.ai.shoes.core.handler;

import cn.ai.shoes.common.pojo.entity.CommonResult;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

import static cn.ai.shoes.common.exception.constant.GlobalErrorCodeConstants.UNAUTHORIZED;


public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //打印异常信息
        authException.printStackTrace();
        //将result象转换为json字符串
        String json= JSON.toJSONString(CommonResult.error(UNAUTHORIZED));
        //设置响应头
        response.setContentType("application/json;charset=utf-8");
        //设置状态码
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        //设置响应体
        response.getWriter().print(json);
    }
}
